package com.usbserial.transaction;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * Wrapper around {@link TerminatedFrameDecoder} that converts byte frames to strings.
 */
public class TerminatedStringDecoder implements FrameDecoder<String> {

    private final TerminatedFrameDecoder delegate;
    private final Charset charset;

    public TerminatedStringDecoder(byte[] terminator, int maxBufferLength, boolean stripTerminator, Charset charset) {
        this.delegate = new TerminatedFrameDecoder(terminator, maxBufferLength, stripTerminator);
        this.charset = charset == null ? StandardCharsets.UTF_8 : charset;
    }

    public TerminatedStringDecoder(byte[] terminator) {
        this(terminator, 1024, true, StandardCharsets.UTF_8);
    }

    @Override
    public List<String> decode(byte[] chunk) {
        List<byte[]> frames = delegate.decode(chunk);
        List<String> result = new ArrayList<>(frames.size());
        for (byte[] frame : frames) {
            result.add(new String(frame, charset));
        }
        return result;
    }

    @Override
    public void reset() {
        delegate.reset();
    }

    @Override
    public void close() {
        delegate.close();
    }
}
